import axios from 'axios';
import store from '@/store';
import qs from 'qs'
import { getHeaders, redirectToLogin } from '@/utils/cookie';

const service = axios.create({
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  // easy-mock服务挂了，暂时不使用了
  // baseURL: 'https://www.easy-mock.com/mock/592501a391470c0ac1fab128',
  baseURL: function () {
    let hp = window.location.protocol
    let host = window.location.host
    // console.log(url)
    return `${hp}//${host}`
    // return 'http://localhost:9098'
  }(),
  paramsSerializer: params => {
  return qs.stringify(params, { indices: false })
},
  timeout: 60000
});

service.interceptors.request.use(
  config => {
    if (store.state.sys.token) config.headers = getHeaders();
    return config;
  },
  error => {
    return Promise.reject();
  }
);

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.config.responseType === 'blob') {
        return response
      } else {
        return response.data;
      }
    } else {
      Promise.reject();
    }
  },
  error => {
    if (error.response.status === 403) {
      redirectToLogin();
    }
    return Promise.reject();
  }
);

export default service;
